const uglifycss = require('uglifycss');

/**
 * 获取scopeId
 */
exports.getId = function () {
    return "data-v-" + Math.random().toString(36).slice(2, 10);
};

/**
 * 图片转换为base64
 */
exports.imageToBase64 = function (content, path) {
    // TODO:转换base64的操作可以使用postcss-base64
};

/**
 * 格式化输出结果
 */
exports.minify = function (input) {
    if (!input)
        return '';

    return uglifycss.processString(input, {
        uglyComments: true,
        cuteComments: true
    });
}

/**
 * 添加socpeid
 */
exports.addScopeIdToStyle = function (style, id) {
    if (!style) {
        throw new Error('样式为空');
    }

    let splitted = style.split(/\{/);
    let selectors = splitted.shift();
    let changedSelectors = [];
    selectors.split(',').forEach(selector => {
        let splitedSelector = selector.trim().split(' ');
        let firstPart = splitedSelector.shift();
        let changedPart = [];

        // 处理伪类选择器，嵌套选择器只处理第一个
        if (firstPart.includes(':')) {
            let splittedPart = firstPart.split(':');
            changedPart.push(splittedPart.shift() + `[${id}]` + splittedPart.join(':'));
        } else {
            changedPart.push(`${firstPart}[${id}]`);
        }

        changedSelectors.push(changedPart.join('') + ' ' + splitedSelector.join(''));
    });

    return changedSelectors.join(',') + '{' + splitted.join('');
};
